package com.kyxx.topics.net;

import android.content.Context;

import com.kyxx.topics.utils.Constants;
import com.kyxx.topics.utils.Log;
import com.kyxx.topics.utils.NetworkUtils;
import com.kyxx.topics.utils.ToastUtils;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.PersistentCookieStore;
import com.loopj.android.http.RequestParams;

import java.io.InputStream;
import java.util.List;

import cz.msebera.android.httpclient.client.params.ClientPNames;
import cz.msebera.android.httpclient.cookie.Cookie;

/**
 * @author txiuqi
 */
public class RestClient {

    private static AsyncHttpClient client = new AsyncHttpClient();

    public static void get(String url, Context context,
                           AsyncHttpResponseHandler responseHandler) {
        if(NetworkUtils.isAvailable(context)){
            client.get(url, null, responseHandler);
        }else{
            ToastUtils.show(context,"网络连接超时");
        }
    }

    public static void post(String url, RequestParams params, Context context,
                            AsyncHttpResponseHandler responseHandler) {
        if(NetworkUtils.isAvailable(context)){
            try {
                PersistentCookieStore myCookieStore = new PersistentCookieStore(context);
                List<Cookie> cookieList = myCookieStore.getCookies();
                for (Cookie cookie : cookieList) {
                    myCookieStore.addCookie(cookie);
                }
                client.setCookieStore(myCookieStore);
                client.getHttpClient().getParams()
                        .setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
                client.post(context, url, params, responseHandler);
                client.setTimeout(Constants.TIME_OUT);
                Log.e("ok", "getRequest" + url);
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            }
        }else{
            ToastUtils.show(context,"网络连接超时");
        }

    }

    public static void postHasError(String url, RequestParams params,
                                    Context context, AsyncHttpResponseHandler responseHandler) {
        try {
            client.post(context, url, params, responseHandler);
            client.setTimeout(Constants.TIME_OUT);
            Log.e("ok", "getRequest" + url);
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }

    public static void cancelRequest(Context context) {
        client.cancelRequests(context, true);
    }
}